<template>
  <q-page class="q-pa-md wrapBox" v-loading="loading">
    <div class="nav">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <el-image src="/svgs/modelApplication.svg" style="width: 17px;margin-top: 2px" fit />
        </el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'model-deploy' }">模型部署</el-breadcrumb-item>
        <el-breadcrumb-item><span style="color: #333;">新建部署</span></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="datasetBox" style="position: relative">
      <div class="contentBox_title">
        <span>新建部署</span>
      </div>
      <div class="contentBox">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm typeBox"
          style="max-width: 70%;" status-icon>
          <el-form-item label="服务名称：" prop="title">
            <el-input v-model.trim="ruleForm.title" placeholder="请输入服务名称" show-word-limit spellcheck="false"
            style="width: 350px;" />
          </el-form-item>
          <el-form-item label="描述：" prop="description">
            <el-input v-model.trim="ruleForm.description" type="textarea" spellcheck="false" placeholder="请输入" :rows="3"
            show-word-limit maxlength="100" style="width: 350px;" />
          </el-form-item>
          <el-form-item label="选择模型" prop="repository_model_id">
            <el-select v-model="ruleForm.repository_model_id" class="m-2" placeholder="请选择仓库模型"
            style="width: 200px;margin-right: 10px;">
              <el-option v-for="item in repositoryAllModel" :key="item.id" :label="item.title" :value="item.id"
              @click="getModelVersions(item.id)" />
            </el-select>
          </el-form-item>
          <el-form-item label="选择模型版本" prop="repository_model_version">
            <el-select v-model="ruleForm.repository_model_version" class="m-2" placeholder="请选择仓库模型"
            style="width: 200px;margin-right: 10px;">
              <el-option v-for="item in repositoryModelVersion" :key="item.id" :label="item.version_number"
              :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="集群队列" prop="queue">
            <el-select v-model="ruleForm.queue" class="m-2" placeholder="请选择仓库模型" style="width: 200px;margin-right: 10px;">
              <el-option v-for="item in modelQueuesList" :key="item.name" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="部署资源" prop="source">
            <el-row>
              <el-col span="20" style="display: flex;margin-right: 25px">
                <span style="color: #1D1D1D;">CPU核数</span>
                <el-input v-model.trim="ruleForm.source.cpu" placeholder="请输入"
                style="width: 100px;margin: 0 10px"></el-input>核
              </el-col>
              <el-col span="20" style="display: flex;margin-right: 25px">
                <span style="color: #1D1D1D;">内存</span>
                <el-input v-model.trim="ruleForm.source.gpu" placeholder="请输入"
                style="width: 100px;margin: 0 10px"></el-input>M
              </el-col>
              <el-col span="20" style="display: flex">
                <span style="margin-right: 5px;color: #1D1D1D;">CPU卡数</span>
                <el-input v-model.trim="ruleForm.source.memory" placeholder="请输入"
                style="width: 100px;margin: 0 10px"></el-input>卡
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="自动停止" prop="delivery">
            <div>
              <el-row>
                <el-col span="20" style="margin-right: 10px"><el-switch v-model="ruleForm.is_auto_stop" /></el-col>
                <el-col span="20" v-if="ruleForm.is_auto_stop">
                  <span style="margin-right: 5px;color: #1D1D1D;">时长</span>
                  <el-input v-model.trim="ruleForm.stop_in_seconds" placeholder="请输入" style="width: 100px;margin: 0 10px"
                  oninput="value=value.replace(/[^\d]/g,'')">></el-input>小时
                </el-col>
              </el-row>
              <el-row v-if="ruleForm.is_auto_stop">
                <p>作业训练达到最大时间会被强制停止,若训练未完成可能造成作业失效</p>
              </el-row>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="row" style="justify-content: end;margin-top: 10px;background-color: #fff;padding: 10px 0 ">
        <el-button v-if="!store.quickStart.quickFlow" @click="resetForm(ruleFormRef)" style="background-color: #fff">取消</el-button>
        <el-button v-if="!store.quickStart.quickFlow" type="primary" @click="submitForm(ruleFormRef)">
          完成创建
        </el-button>
        <el-button v-if="store.quickStart.quickFlow" type="primary" @click="submitForm(ruleFormRef)">
          创建并跳转到服务详情
        </el-button>
      </div>
    </div>
  </q-page>
</template>
<script setup lang="ts">
const loading = ref(false)
import { ref, reactive, shallowRef, toRaw } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import {
  model_is_title_exists,
  getProjectRepositoryModels,
  getProjectRepositoryModelsVersion,
  getModelQueues,
  getModelDeployments
} from "src/api/model";
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';
import { dataSetStore } from 'src/stores/dataSet'
import { modelStore } from "stores/model";
import { putQuickStartFlow } from 'src/api/project'
const store = dataSetStore()
const router = useRouter()
const projectId = router.currentRoute.value.params.project_id;
const ruleFormRef = ref<FormInstance>()
interface useInfoModel {
  title: string;
  description: string;
  repository_model_id: string;
  queue: string;
  repository_model_version: string;
  source: any,
  is_auto_stop: boolean,
  stop_in_seconds: string
}
const ruleForm = reactive<useInfoModel>({
  title: '',
  description: '',
  repository_model_id: '',
  repository_model_version: '',
  queue: '',
  source: {
    cpu: '',
    memory: '',
    gpu: ''
  },
  is_auto_stop: false,
  stop_in_seconds: ''
})
const repositoryAllModel = ref([]);
const repositoryModelVersion = ref([]);
const modelQueuesList = ref([]);
// 表单校验

const validateTitle = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('服务名称不能为空'))
    return
  }
  let params = {
    title: ruleForm.title
  }
  model_is_title_exists(projectId, params).then(res => {
    if (res.data.exists) {
      callback(new Error('服务名称名称重复'))
    }
    callback()
  }).catch(err => {
    callback(new Error('校验接口报错'))
  })
}
let newRule = (rule: any, value: any, callback: any) => {
  if (value.cpu === '') {
    callback(new Error('请输入CPU核数'))
  } else if (value.memory === '') {
    callback(new Error('请输入内存数'))
  } else if (value.gpu === '') {
    callback(new Error(`请输入CPU卡数`))
  } else {
    callback()
  }
}
const rules = reactive<FormRules>({
  title: [
    { required: true, validator: validateTitle, trigger: 'blur' }
  ],
  repository_model_id: [
    { required: true, message: '请选择模型', trigger: 'blur' }
  ],
  repository_model_version: [
    { required: true, message: '请选择模型版本', trigger: 'blur' }
  ],
  queue: [
    { required: true, message: '请选择集群队列', trigger: 'blur' }
  ],
  source: [
    { required: true, validator: newRule }
  ]
})

//行为触发
getAllModels();//获取模型列表
getQueues();//获取模型部署队列

//获取所有仓库模型
function getAllModels() {
  getProjectRepositoryModels(projectId).then((res: any) => {
    repositoryAllModel.value = res.data;
  })
}
//获取模型下的版本列表
function getModelVersions(id: any) {
  getProjectRepositoryModelsVersion(projectId, id).then((res: any) => {
    repositoryModelVersion.value = res.data;
  })
}
//获取模型队列
function getQueues() {
  getModelQueues().then((res: any) => {
    modelQueuesList.value = res.data;
  })
}


//取消
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  router.push({ name: 'model-deploy', params: { project_id: projectId } })
}
//创建
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const { title, description, repository_model_version, queue, source, is_auto_stop, stop_in_seconds } = ruleForm
      const params = {
        title,
        description,
        repository_model_version,
        queue,
        cpu: source.cpu,
        gpu: source.gpu,
        memory: source.memory,
        is_auto_stop: is_auto_stop,
        stop_in_seconds: stop_in_seconds ? stop_in_seconds : 0
      }
      getModelDeployments(projectId, params).then((res: any) => {
        ElMessage.success("模型部署成功");
        if (store.quickStart.quickFlow) {
          putQuickStartFlow(projectId, { stage: 0 }).finally(() => {
            modelStore().dataset(res.data.id);
            router.push({ name: 'model-deploy-detail' })
          })

        } else {
          router.push({ name: 'model-deploy', params: { project_id: projectId } })
        }

      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>
<style scoped lang="scss">
.wrapBox {
  padding: 0 !important;
  .nav {
    display: flex;
    align-items: center;
    padding-left: 20px;
    cursor: pointer;
    background-color: var(--nav-bg-color);
    height: 46px;
    ::v-deep .el-breadcrumb{
      display: flex;
      align-items: center;
    }
  }
  .datasetBox {
    margin: 0 20px;
    .contentBox_title{
      position: relative;
      display: flex;
      align-items: center;
      color: var(--title);
      font-weight: 500;
      font-size: 16px;
      padding: 15px 15px;
      border-bottom: 1px solid #e5e6eb;
      background-color: #ffffff !important;
      .icon{
        position: absolute;
        left: 90px;
        top: 22px;
        width: 17px;
      }
      .text{
        position: absolute;
        left: 104px;
        top: 19px;
        font-size: 12px;
        color: #3d5ce4;
        font-weight: 400;
        cursor: pointer;
      }
    }
    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
      .searchWrap{
        display: flex;
        justify-content: space-between;
      }
    }
  }
}
//面包屑斜杆
::v-deep .el-breadcrumb__separator {
  font-size: 14px !important;
  color: #c9cdd4 !important;
  margin-top: 2px !important;
}
//面包屑字体颜色
::v-deep .el-breadcrumb__inner {
  color: #666 !important;
}
::v-deep .el-breadcrumb__inner.is-link,
.el-breadcrumb__inner a {
  font-weight: normal !important;
}
</style>
